import config from '../config/config'

function request(url,param,isShowLoading) {
	if(isShowLoading!==false){
		uni.showLoading({ title: '', mask:true});
	}
	return  new Promise((resolve, reject) => {  
		uni.request({
			url: (config.debug == true ? config.debugUrl : config.serverUrl) + url,
			data: param || {},
			method:"POST",
			header: {
				'content-type': 'application/x-www-form-urlencoded', 
				'authorization': uni.getStorageSync('access_token'),
			},
			dataType:'json',
			success: (res) => {
				if(isShowLoading!==false){
					uni.hideLoading();
				}
				if(res.statusCode != 200){
					uni.showToast({
						icon: 'none',
						position:"top",
						title:"系统异常:" + res.statusCode,
					});
					reject(res);
					return false;
				}
				let data = res.data;
				if(data.code==-1){
					uni.showToast({
						icon: 'none',
						position:"top",
						title: data.msg || "网络错误",
					});
					reject(res);
					return false;
				}
				if(data.code==-2){
					uni.showModal({
						icon: 'none',
						position:"top",
						title:"提示",
						showCancel:false,
						content:data.msg || "网络错误"
					});
					reject(res);
					return false;
				}
				if(data.code==-10){
					uni.setStorageSync('access_token', "");
					uni.setStorageSync('refresh_token', "");
					if(this && this.$store){ this.$store.commit('logout'); }
					uni.showModal({
						icon: 'none',
						position:"top",
						title:"提示",
						showCancel:false,
						content:data.msg || "账号异常",
						success:function(){
							//wx-web 微信公众号登录模式
							if( config.webMode == 'wx-web' && window.WeixinJSBridge){
								//这个可以关闭安卓系统的手机
								document.addEventListener('WeixinJSBridgeReady', function(){
									WeixinJSBridge.call('closeWindow'); 
								}, false);
								//这个可以关闭ios系统的手机
								WeixinJSBridge.call('closeWindow');
								return false;				
							}else if( config.webMode == 'wx-app'){
								uni.reLaunch({ url: '/pages/greet'});
								return false;
							}else{
								uni.reLaunch({ url: '/pages/login/login'});
							}
							reject(res);
						}
					});
					return false;
				}
				// accessToken过期 请求刷新token
				if(data.code==-101){
					request(data.data,{
						refresh_token: uni.getStorageSync('refresh_token') || '-1'
					},false).then(function(res){
						uni.setStorageSync('access_token', res.data.access_token);
						uni.setStorageSync('refresh_token', res.data.refresh_token);
						request(url,param,isShowLoading).then(function(res){
							resolve(res.data);
						});
					});
					return false;
				}
				resolve(res.data);
			},
			fail:(res) => {
				if(isShowLoading!==false){
					uni.hideLoading();
				}
				uni.showToast({icon: 'none',title: '请求异常'});
				reject(res);
			}
		});
	})  
}

module.exports = request;